# -*- coding: utf-8 -*-
import hashlib
import json
import logging
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils.exceptions import ParamError
from common.utils.qr import make_code

_LOGGER = logging.getLogger(__name__)

APP_CONF = {
    '3093': {
        #  稳付 支付宝3.7，微信3.9    最新2019-7
        'API_KEY': '065ef963dd32e58472733f38b634c9ba',
    },
    # '2081': {
    #     #  稳付 支付宝宝到卡扫码 2.3% 100-5000 dwc
    #     'API_KEY': 'a32356331cf2a7f56e45306fc6d328d9',
    # },
    # '2082': {
    #     #  稳付 支付宝宝到卡扫码 2.3% 100-5000 dwc
    #     'API_KEY': '0a9b52fb6605edc74fd7d5359f34477e',
    # },
    # '2096': {
    #     #  稳付 支付宝宝到卡扫码 2.3% 100-5000 dwc
    #     'API_KEY': '5b1d59b5451c06afb65ab1bc2713cfb4',
    # },
    'gateway': 'https://api.wenpay8.com/PaymentGetway/OrderRquest',
    'query_gateway': 'https://api.wenpay8.com/PaymentGetway/OrderQuery',
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def gen_order_sign(d, key):
    s = 'merchantId={}&merchantOrderId={}&orderAmount={}&notifyUrl={}&channelType={}&remark={}&ip={}{}'.format(
        d['merchantId'], d['merchantOrderId'], d['orderAmount'], d['notifyUrl'], d['channelType'], d['remark'], d['ip'],
        key
    )
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = 'merchantId={}&merchantOrderId={}&orderAmount={}&systemOrderId={}&channelType={}&remark={}&ip={}{}'.format(
        d['merchantId'], d['merchantOrderId'], d['orderAmount'], d['systemOrderId'], d['channelType'], d['remark'],
        d['ip'], key
    )
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'merchantId={}&merchantOrderId={}&orderAmount={}{}'.format(
        d['merchantId'], d['merchantOrderId'], d['orderAmount'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("wenfupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'wechat_scan':
        return 'C100'
    elif service == 'wechat_wap':
        return 'C101'
    elif service == 'alipay_scan':
        return 'C200'
    elif service == 'alipay_wap':
        return 'C201'
    elif service == 'quick_pay':
        return 'QUICK_PAY'
    return 'C200'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantId', app_id),
        ('merchantOrderId', str(pay.id)),
        ('orderAmount', str(pay_amount)),
        ('channelType', _get_pay_type(service)),
        ('notifyUrl', '{}/pay/api/{}/wenfupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnUrl', '{}/pay/api/{}/wenfupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('ip', _get_device_ip(service)),
        ('remark', 'Charge'),
        ('jsonResult', '1'),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("wenfupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['merchantOrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(), data=parameter_dict, headers=headers, timeout=3, verify=False)
    data = json.loads(response.text)
    _LOGGER.info('wenfupay create response data:%s' % data)
    if data['ErrorMessage']:
        return {'charge_info': data['ErrorMessage']}
    if service in ['wechat_wap', 'alipay_wap', 'wechat_scan', 'quick_pay']:
        return {'charge_info': data['Qrcode']}
    else:
        template_data = {'base64_img': make_code(data['Qrcode']), 'amount': pay_amount}
        t = get_template('qr_alipay_wenfu.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("wenfupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("wenfupay notify data: %s, order_id is: %s", data, data['merchantOrderId'])
    verify_notify_sign(data, api_key)
    pay_id = data['merchantOrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('wenfupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    trade_no = data['systemOrderId']
    total_fee = float(data['orderAmount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 凡是发送通知的订单均为交易成功的订单
    if data:
        _LOGGER.info('wenfupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantId', app_id),
        ('merchantOrderId', pay_order.id),
        ('orderAmount', str(pay_order.total_fee)),
    ))
    parameter_dict['sign'] = gen_query_sign(parameter_dict, api_key)
    _LOGGER.info("wenfupay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(), data=parameter_dict, headers=headers)
    _LOGGER.info("wenfupay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['ErrorCode'])
        trade_no = pay_order.third_id
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        check_channel_order(pay_id, total_fee, app_id)
        if trade_status == '00':
            _LOGGER.info('wenfupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('wenfupay data error, status_code: %s', response.status_code)
